//
//  HLFeedbackViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/19.
//

#import "HLFeedbackViewController.h"
#import "HLUserOptionRequest.h"
#import "HLPickerManager.h"
#import "HLOSSManager.h"
#import "HLImageStatusView.h"

@interface HLFeedbackViewController ()<QMUITextViewDelegate, QMUITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *contentTitleLabel;
@property (nonatomic, strong) QMUITextView *textView;
@property (nonatomic, strong) UILabel *textCountLabel;
@property (nonatomic, strong) UILabel *imageTipLabel;
@property (nonatomic, strong) QMUIFloatLayoutView *imagesView;
@property (nonatomic, strong) UILabel *connectTitleLabel;
@property (nonatomic, strong) QMUITextField *titleTextField;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) QMUIButton *startButton;
@property (nonatomic, strong) HLPickerManager *pickerManager;
@property (nonatomic, strong) HLOSSManager *ossManager;
@property (nonatomic, strong) NSMutableArray <HXPhotoModel *> * photos;
@property (nonatomic, strong) NSMutableArray <UIImage *> *imagesArray;

@end

@implementation HLFeedbackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorWhite;
    self.photos = [NSMutableArray array];
    self.imagesArray = [NSMutableArray array];
    self.pickerManager = [[HLPickerManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto avatar:NO];
    [self.pickerManager updateMaxNum:3 photos:[self.photos copy]];
    self.ossManager = [[HLOSSManager alloc] initWithOSSPath:@"feedback"];
}


- (void)setupNavigationItems
{
    [super setupNavigationItems];
    self.title = @"意见与反馈";
}


- (void)initSubviews
{
    [super initSubviews];
    self.scrollView = [[UIScrollView alloc] init];
    [self.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.contentView = [[UIView alloc] init];
    [self.scrollView addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    
    self.contentTitleLabel = [[UILabel alloc] init];
    _contentTitleLabel.textColor = HLTextColor1;
    _contentTitleLabel.font = UIFontMake(16);
    _contentTitleLabel.text = @"请输入您的宝贵意见";
    [_contentView addSubview:_contentTitleLabel];
    [_contentTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.top.mas_equalTo(NavigationContentTopConstant + 24);
    }];
    
    [HLUIHelper showRequiredLabelWithView:_contentTitleLabel];
    
    self.textView = [[QMUITextView alloc] init];
    _textView.placeholder = @" 请填写您的建议，感谢您的支持～（必填）";
    _textView.font = UIFontMake(14);
    _textView.textColor = HLTextColor1;
    _textView.contentInset = UIEdgeInsetsMake(12, 12, 12, 12);
    _textView.backgroundColor = HLBackgroundColor;
    _textView.maximumTextLength = 200;
    _textView.delegate = self;
    [_contentView addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.top.equalTo(_contentTitleLabel.mas_bottom).offset(12);
        make.height.mas_equalTo(170);
    }];
    
    self.textCountLabel = [[UILabel alloc] init];
    _textCountLabel.font = UIFontMake(12);
    _textCountLabel.textColor = HLTextColor2;
    _textCountLabel.text = @"0/200";
    [_contentView addSubview:_textCountLabel];
    [_textCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(_textView).offset(-12);
    }];
    
    self.imageTipLabel = [[UILabel alloc] init];
    _imageTipLabel.font = UIFontMake(15);
    _imageTipLabel.textColor = HLTextColor1;
    _imageTipLabel.text = @"图片（0/3）选填";
    [_contentView addSubview:_imageTipLabel];
    [_imageTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.top.equalTo(_textView.mas_bottom).offset(34);
    }];

    self.imagesView = [[QMUIFloatLayoutView alloc] init];
    _imagesView.padding = UIEdgeInsetsMake(6, 6, 6, 6);
    _imagesView.itemMargins = UIEdgeInsetsMake(0, 1, 0, 1);
    _imagesView.minimumItemSize = CGSizeMake(102, 102);// 以2个字的按钮作为最小宽度
    _imagesView.maximumItemSize = CGSizeMake(102, 102);
    [self.contentView addSubview:_imagesView];
    [_imagesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(140);
        make.top.equalTo(_imageTipLabel.mas_bottom).offset(18);
    }];
    
    QMUIButton *uploadButton = [[QMUIButton alloc] init];
    [uploadButton setImage:UIImageMake(@"edit_cell_image") forState:UIControlStateNormal];
    [uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
    [uploadButton setBackgroundColor:HLBackgroundColor];
    uploadButton.cornerRadius = 4;
    [_imagesView addSubview:uploadButton];
    
    self.connectTitleLabel = [[UILabel alloc] init];
    _connectTitleLabel.textColor = HLTextColor1;
    _connectTitleLabel.font = UIFontMake(16);
    _connectTitleLabel.text = @"请输入您的联系方式";
    [_contentView addSubview:_connectTitleLabel];
    [_connectTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.top.equalTo(_imagesView.mas_bottom).offset(24);
    }];
    
    [HLUIHelper showRequiredLabelWithView:_connectTitleLabel];
    
    self.titleTextField = [[QMUITextField alloc] init];
    [_titleTextField setBackgroundColor:HLBackgroundColor];
    [_titleTextField setPlaceholder:@"请输入您的联系手机号码"];
    _titleTextField.layer.masksToBounds = YES;
    _titleTextField.layer.cornerRadius = 4;
    _titleTextField.delegate = self;
    _titleTextField.font = UIFontMake(14);
    [_contentView addSubview:_titleTextField];
    [_titleTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_textView);
        make.top.equalTo(_connectTitleLabel.mas_bottom).offset(12);
        make.height.mas_equalTo(52);
    }];

    
    self.startButton = [[QMUIButton alloc] init];
    [_startButton setTitle:@"提交" forState:UIControlStateNormal];
    [_startButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_startButton.titleLabel setFont:UIFontMake(15)];
    [_startButton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    _startButton.cornerRadius = 4;
    _startButton.enabled = NO;
    [_startButton setBackgroundColor:HLMainColor];
    [self.view addSubview:_startButton];
    [_startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_titleTextField);
        make.height.mas_equalTo(52);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 40));
    }];

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_titleTextField.mas_bottom).offset(44);
    }];
}


- (void)updateWithPhoto:(NSArray<HXPhotoModel *> *)models
{
    [_imagesView qmui_removeAllSubviews];
    [_imagesArray removeAllObjects];
    self.photos = [NSMutableArray arrayWithArray:models];
    [self.pickerManager updateMaxNum:3 photos:models];
    _imageTipLabel.text = [NSString stringWithFormat: @"图片（%ld/3）选填", models.count];
    if (models.count > 0){
        MJWeakSelf;
        for (HXPhotoModel *m in models) {
            [m getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                
                [weakSelf.imagesArray addObject:image];
                
                HLImageStatusView *imageButton = [[HLImageStatusView alloc] init];
                [imageButton.imageView setContentMode:UIViewContentModeScaleAspectFill];
                [imageButton.imageView setImage:image];
                imageButton.statusLabel.hidden = YES;
                [imageButton.closeButton addTarget:self action:@selector(delAction:) forControlEvents:UIControlEventTouchUpInside];
                [imageButton setBackgroundColor:HLBackgroundColor];
                imageButton.layer.cornerRadius = 4;
                imageButton.closeButton.tag = [models indexOfObject:m];
                [weakSelf.imagesView addSubview:imageButton];
                if (models.count < 3 && weakSelf.imagesView.subviews.count == models.count){
                    QMUIButton *uploadButton = [[QMUIButton alloc] init];
                    [uploadButton setImage:UIImageMake(@"edit_cell_image") forState:UIControlStateNormal];
                    [uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
                    [uploadButton setBackgroundColor:HLBackgroundColor];
                    uploadButton.cornerRadius = 4;
                    [weakSelf.imagesView addSubview:uploadButton];
                }
                
            } failed:nil];
        }
    } else {
        if (models.count < 3 && self.imagesView.subviews.count == models.count){
            QMUIButton *uploadButton = [[QMUIButton alloc] init];
            [uploadButton setImage:UIImageMake(@"edit_cell_image") forState:UIControlStateNormal];
            [uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
            [uploadButton setBackgroundColor:HLBackgroundColor];
            uploadButton.cornerRadius = 4;
            [self.imagesView addSubview:uploadButton];
        }
    }
    
    
    
}

- (void)delAction:(UIButton *)btn
{
    [self.photos removeObjectAtIndex:btn.tag];
    [self updateWithPhoto:self.photos];
}

- (void)uploadAction
{
    MJWeakSelf;
    [self.pickerManager showWithController:self block:^(NSArray<HXPhotoModel *> * datas) {
        [weakSelf updateWithPhoto:datas];
    }];
}

- (void)saveAction
{
    NSString *connect = _titleTextField.text;
    NSString *content = _textView.text;
    
    if (connect.length < 1){
        [QMUITips showWithText:@"请输入您的联系手机号码"];
        return;
    }
    
    if (content.length < 1){
        [QMUITips showWithText:@"请填写您的建议，感谢您的支持～"];
        return;
    }
    
    if (self.imagesArray.count > 0){
       
        MJWeakSelf;
        [self.ossManager uploadDatas:[self.imagesArray copy] callBack:^(NSArray<NSString *> *urls) {
            [weakSelf feedbackRequestWithImageUrls:urls];
        }];
    } else {
        [self feedbackRequestWithImageUrls:@[]];
    }
    
}

- (void)feedbackRequestWithImageUrls:(NSArray *)urls
{
    NSString *urlString = [urls componentsJoinedByString:@","];
    NSDictionary *params = @{@"contactPhoneNo": _titleTextField.text, @"content": _textView.text, @"imgUrl":urlString};
    HLUserOptionRequest *userOptionRequest = [[HLUserOptionRequest alloc] initWithType:HLUserOptionTypeFeedback params:params];
    [userOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLUserOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:nil];
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view
{
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDarkContent;
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:HLBackgroundColor];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorBlack;
}


#pragma QMUITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    self.textCountLabel.text = [NSString stringWithFormat:@"%ld/200", textView.text.length];
    [self updateButtonEnable];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self updateButtonEnable];
}


- (void)updateButtonEnable
{
    _startButton.enabled = (_titleTextField.text.length > 4 && _textView.text.length > 4);
}


@end
